#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<unistd.h>
#include <fcntl.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<arpa/inet.h>
#include<event2/event.h>
#include<event2/listener.h>
#include<event2/bufferevent.h>
#define SERVICE_PORT 9527
//需求使用libevent库实现客户端的写数据

//客户端写数据给服务器
//void (*evconnlistener_cb)(struct evconnlistener*listener,evutil_socket_t fd,struct sockaddr*addr,int len,void*ptr)
void write_cb(struct bufferevent*buffevent,void*arg){
      char buf[1024];
      int n=bufferevent_read(buffevent,buf,sizeof(buf));//buffevent里面包含了文件描述符
      buf[n]='\0';
}

//监听用户输入的数据
void stdout_read(evutil_socket_t fd,short what,void*arg){
       char buf[1024];
       int len=read(STDIN_FILENO,buf,sizeof(buf));
       struct bufferevent*ev;
       ev=(struct bufferevent*)arg;
       bufferevent_write(ev,buf,len+1);
}
int main(){

   //创建基座 
   struct event_base*base;
   base=event_base_new();
    
   int fd=socket(AF_INET,SOCK_STREAM,0);   //客户端使用的套接字
   //创建bufferevent事件通信对象事件
   struct bufferevent*ev;
   ev=bufferevent_socket_new(base,fd,BEV_OPT_CLOSE_ON_FREE);
   
   //绑定服务器的端口和ip地址
   struct sockaddr_in saddr;
   saddr.sin_family=AF_INET;
   saddr.sin_port=htons(SERVICE_PORT);
   saddr.sin_addr.s_addr=htonl(INADDR_ANY);
   
   //建立连接
   printf("-----------------1\n");
   bufferevent_socket_connect(ev,(struct sockaddr*)&saddr,sizeof(saddr));   
   printf("-----------------2\n");
   //设置回调函数
   bufferevent_setcb(ev,NULL,write_cb,NULL,NULL);
   printf("-----------------3\n");
   //创建事件监听标准输出
   struct event*ev1=event_new(base,STDIN_FILENO,EV_READ|EV_PERSIST,stdout_read,ev);
   event_add(ev1,NULL);
   printf("-----------------4\n");
   //循环监听事件
   event_base_dispatch(base);

   //释放
   event_base_free(base);
   return 0;
}